<route lang="json5" type="page">
{
  style: {
    navigationBarTitleText: '打卡',
    navigationBarBackgroundColor: '#f8f8f8',
    navigationBarTextStyle: 'black'
  },
}
</route>

<script setup lang="ts">
import type {
  PunchCreateReqVO,
  PunchUpdateReqVO,
} from '@/api/types/punch'
import type { ReadingHistoryRespVO } from '@/types/reading-records'
import { onLoad } from '@dcloudio/uni-app'
import { computed, ref } from 'vue'
import {
  createPunch,
  getPunchDetail,
  updatePunch,
} from '@/api/punch'
import {
  getTodayReadingRecords,
} from '@/api/reading-records'

// 页面数据
const todayBookCount = computed(() => todayBooks.value.length) // 今天阅读的书籍数量
const checkinContent = ref('') // 打卡心得内容
const isSubmitting = ref(false) // 是否正在提交
const loading = ref(false) // 数据加载状态

// 今日阅读的绘本列表
const todayBooks = ref<ReadingHistoryRespVO[]>([])

// 打卡记录ID（用于判断是新建还是更新）
const existingCheckinId = ref<number | null>(null)

// 显示的绘本逻辑
const displayBooks = computed(() => {
  if (todayBooks.value.length <= 3) {
    // 3本或以下，显示全部
    return todayBooks.value
  }
  else {
    // 超过3本，只显示前2本
    return todayBooks.value.slice(0, 2)
  }
})

// 是否显示更多按钮
const showMoreBooks = computed(() => {
  return todayBooks.value.length > 3
})

// 图片加载错误处理
function onImageError(event: any) {
  console.log('图片加载失败:', event)
  // 可以设置默认图片
}

// 显示今日绘本弹窗
const showAllBooksModal = () => {
  showAllBooksModalVisible.value = true
}

// 隐藏今日绘本弹窗
const hideAllBooksModal = () => {
  showAllBooksModalVisible.value = false
}

// 加载今日阅读数据
async function loadTodayReading() {
  try {
    loading.value = true
    console.log('打卡页面：开始加载今日阅读记录...')
    const response = await getTodayReadingRecords()
    console.log('打卡页面：API响应:', response)

    // 检查不同的响应格式
    let todayData
    if (response.data && response.data.code === 0) {
      // 格式1: {data: {code: 0, data: {readBookCount: 4, bookList: [...]}}}
      todayData = response.data.data
    }
    else if (response.data && response.data.readBookCount !== undefined) {
      // 格式2: {data: {readBookCount: 4, bookList: [...]}}
      todayData = response.data
    }
    else if (response.readBookCount !== undefined) {
      // 格式3: {readBookCount: 4, bookList: [...]}
      todayData = response
    }
    else {
      console.warn('打卡页面：无法识别的API响应格式:', response)
      todayBooks.value = []
      return
    }

    const bookList = todayData?.bookList || []
    console.log('打卡页面：获取到绘本列表:', bookList, '数量:', bookList.length)

    // 转换数据格式以匹配ReadingHistoryRespVO
    todayBooks.value = bookList.map((book: any) => {
      // 处理时间格式：如果是时间戳则转换为ISO字符串
      let readAtStr = book.readAt
      if (typeof book.readAt === 'number') {
        readAtStr = new Date(book.readAt).toISOString()
      }

      return {
        id: book.id,
        bookId: book.id,
        bookTitle: book.title,
        bookCover: book.cover,
        isCompleted: book.isCompleted,
        readingProgress: book.readingProgress,
        readingTime: 0,
        lastReadAt: readAtStr,
        completedAt: book.isCompleted ? readAtStr : undefined,
      }
    })

    console.log('打卡页面：转换后的数据:', todayBooks.value)
  }
  catch (error) {
    console.error('打卡页面：获取今日阅读记录失败:', error)
    todayBooks.value = []
    uni.showToast({
      title: '获取阅读记录失败',
      icon: 'none',
    })
  }
  finally {
    loading.value = false
  }
}

// 加载打卡详情（编辑模式）
async function loadPunchDetail(punchId: number) {
  try {
    const response = await getPunchDetail(punchId)
    if (response.code === 0 && response.data) {
      checkinContent.value = response.data.commentText || ''
    }
  }
  catch (error) {
    console.error('获取打卡详情失败:', error)
    uni.showToast({
      title: '获取打卡详情失败',
      icon: 'none',
    })
  }
}

// 页面参数
interface PageParams {
  bookCount?: string
  existingContent?: string
  checkinId?: string
  isRepunch?: string // 是否为重新打卡
  punchId?: string // 打卡记录ID
}

// 重新打卡相关状态
const isRepunchMode = ref(false) // 是否为重新打卡模式

// 今日绘本展示弹窗相关
const showAllBooksModalVisible = ref(false)

// 按钮禁用状态
const isButtonDisabled = computed(() => {
  return todayBookCount.value === 0 || isSubmitting.value
})

// 获取按钮文本
function getButtonText() {
  if (isSubmitting.value) {
    return '发布中...'
  }
  if (todayBookCount.value === 0) {
    return '请先阅读绘本'
  }
  return isRepunchMode.value ? '重新打卡' : '发布打卡'
}

// 提交打卡
async function submitCheckin() {
  if (isSubmitting.value)
    return

  // 验证输入
  if (todayBookCount.value === 0) {
    uni.showToast({
      title: '请先阅读绘本再打卡',
      icon: 'none',
    })
    return
  }

  isSubmitting.value = true

  try {
    // 重新打卡模式或普通编辑模式的判断
    const isUpdate = !!existingCheckinId.value && !isRepunchMode.value

    if (isUpdate) {
      // 更新打卡记录（非重新打卡的编辑模式）
      const updateData: PunchUpdateReqVO = {
        commentText: checkinContent.value.trim(),
      }

      const response = await updatePunch(existingCheckinId.value!, updateData)
      if (response.code === 0) {
        uni.showToast({
          title: '打卡更新成功',
          icon: 'success',
          duration: 2000,
        })
      }
      else {
        throw new Error(response.msg || '更新失败')
      }
    }
    else {
      // 创建新打卡记录或重新打卡（后端会自动处理重复打卡逻辑）
      const createData: PunchCreateReqVO = {
        readingTime: todayBooks.value.reduce((total, book) => total + (book.readingTime || 0), 0),
        bookIds: todayBooks.value.map(book => book.bookId),
        commentText: checkinContent.value.trim(),
        isPublic: true, // 添加缺失的字段
      }

      const response = await createPunch(createData)
      if (response.code === 0) {
        const successMessage = isRepunchMode.value ? '重新打卡成功' : '打卡成功'
        uni.showToast({
          title: successMessage,
          icon: 'success',
          duration: 1500,
        })

        // 跳转到打卡展示页面
        setTimeout(() => {
          uni.navigateTo({
            url: `/pages/checkin-result/index?punchId=${response.data}`,
          })
        }, 1500)
        return
      }
      else {
        throw new Error(response.msg || '打卡失败')
      }
    }

    // 更新模式成功后返回上一页
    if (isUpdate) {
      setTimeout(() => {
        uni.navigateBack({
          delta: 1,
        })
      }, 2000)
    }
  }
  catch (error: any) {
    console.error('打卡提交失败:', error)

    // 根据错误码提供更具体的错误信息
    let errorMessage = '打卡失败，请检查网络'
    if (error.message) {
      if (error.message.includes('今日已打卡')) {
        errorMessage = '今日已打卡，无需重复打卡'
      }
      else if (error.message.includes('今日未阅读')) {
        errorMessage = '今日未阅读绘本，无法打卡'
      }
      else if (error.message.includes('阅读心得不能为空')) {
        errorMessage = '请填写阅读心得'
      }
      else {
        errorMessage = error.message
      }
    }

    uni.showToast({
      title: errorMessage,
      icon: 'error',
      duration: 3000,
    })
  }
  finally {
    isSubmitting.value = false
  }
}

// 页面加载
onLoad(async (options: PageParams) => {
  console.log('打卡页面参数:', options)

  // 检查是否为重新打卡模式
  if (options.isRepunch === 'true') {
    isRepunchMode.value = true
    if (options.punchId) {
      existingCheckinId.value = Number.parseInt(options.punchId)
    }
  }

  // 获取传入的参数
  if (options.existingContent) {
    checkinContent.value = decodeURIComponent(options.existingContent)
  }

  if (options.checkinId && !isRepunchMode.value) {
    existingCheckinId.value = Number.parseInt(options.checkinId)
  }

  // 加载今日阅读数据
  await loadTodayReading()

  // 如果是编辑模式，加载打卡详情
  if (existingCheckinId.value && !isRepunchMode.value) {
    await loadPunchDetail(existingCheckinId.value)
  }

  console.log('今日阅读绘本数量:', todayBookCount.value)
  console.log('重新打卡模式:', isRepunchMode.value)
})
</script>

<template>
  <view class="checkin-container">
    <!-- 阅读成果展示 -->
    <view class="reading-result">
      <view class="result-icon">
        <text class="icon-text">
          📚
        </text>
      </view>
      <text class="result-title">
        今天读了{{ todayBookCount }}本书
      </text>
      <!-- <text class="result-subtitle">填写阅读心得，可以为空</text> -->

      <!-- 今日阅读绘本展示 -->
      <view v-if="todayBooks.length > 0" class="books-display">
        <view class="books-grid">
          <view
            v-for="(book, index) in displayBooks"
            :key="book.id"
            class="book-item"
          >
            <image
              class="book-cover"
              :src="book.bookCover"
              mode="aspectFit"
              @error="onImageError"
            />
            <text class="book-title">
              {{ book.bookTitle }}
            </text>
          </view>

          <!-- 更多绘本提示 -->
          <view v-if="showMoreBooks" class="more-books" @click="showAllBooksModal">
            <view class="more-icon">
              <text class="more-text">
                +{{ todayBooks.length - 2 }}
              </text>
            </view>
            <text class="more-title">
              更多
            </text>
          </view>
        </view>
      </view>
    </view>

    <!-- 心得填写区域 -->
    <view class="content-input-section">
      <textarea
        v-model="checkinContent"
        class="content-textarea"
        placeholder="今天的阅读让你有什么收获呢？可以分享最喜欢的情节、学到的新知识、内心的感受等..."
        :maxlength="200"
        auto-height
        :show-confirm-bar="false"
      />
      <view class="char-count">
        <text class="count-text">
          {{ checkinContent.length }}/200
        </text>
      </view>
    </view>

    <!-- 发布打卡按钮 -->
    <view class="publish-section">
      <button
        class="publish-btn"
        :class="{ loading: isSubmitting, disabled: isButtonDisabled }"
        :disabled="isButtonDisabled"
        @click="submitCheckin"
      >
        <text class="btn-text">
          {{ getButtonText() }}
        </text>
      </button>
    </view>

    <!-- 今日绘本展示弹窗 -->
    <view v-if="showAllBooksModalVisible" class="detail-modal-overlay" @click="hideAllBooksModal">
      <view class="detail-modal-content" @click.stop>
        <!-- 关闭按钮 -->
        <view class="modal-close-btn" @click="hideAllBooksModal">
          <wd-icon name="close" size="22px"></wd-icon>
        </view>

        <!-- 滚动容器 -->
        <scroll-view class="modal-scroll-container" :scroll-y="true" :enhanced="true" :show-scrollbar="false">
          <!-- 标题 -->
          <view class="modal-books-header">
            <view class="books-header">
              <text class="books-icon">📚</text>
              <text class="books-title">今日阅读绘本</text>
            </view>
            <text class="books-count">共{{ todayBooks.length }}本</text>
          </view>

          <!-- 分割线 -->
          <view class="modal-divider"></view>

          <!-- 绘本网格 -->
          <view class="modal-books-section">
            <view class="modal-books-grid">
              <view v-for="book in todayBooks" :key="book.id" class="modal-book-item">
                <image class="modal-book-cover" :src="book.bookCover" mode="aspectFill" @error="onImageError" />
                <text class="modal-book-title">{{ book.bookTitle }}</text>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
// 导入公共样式变量
@import '@/styles/variables.scss';

.checkin-container {
  background: $bg-gradient;
  // min-height: calc(100vh - 100px);
  height: 100vh;
  padding: $container-padding;
  padding-top: 0px;
  padding-bottom: 0px;
  display: flex;
  flex-direction: column;
}

/* 阅读成果展示 - 毛玻璃卡片风格 */
.reading-result {
  padding: $spacing-3xl $spacing-2xl;
  margin: $spacing-md;
  position: relative;
  text-align: center;
  border-radius: $border-radius-xl;
  overflow: hidden;

  /* 毛玻璃背景 */
  @include glass-effect(0.25);
  backdrop-filter: blur(24px);
  border: 2px solid $white-80;
  box-shadow:
    20px 20px 60px rgba(0, 0, 0, 0.1),
    -20px -20px 60px rgba(255, 255, 255, 0.1);

  /* 动态背景blob */
  &::before {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    width: 200px;
    height: 200px;
    border-radius: $border-radius-full;
    background: $blue-gradient;
    opacity: 0.3;
    filter: blur(40px);
    z-index: 1;
    animation: blob-bounce 8s infinite ease-in-out;
    transform: translate(-50%, -50%);
  }

  /* 确保内容在blob之上 */
  .result-icon,
  .result-title,
  .result-subtitle,
  .books-display {
    position: relative;
    z-index: 2;
  }

  .result-icon {
    margin-bottom: $spacing-lg;

    .icon-text {
      font-size: 48px;
      display: block;
      animation: bounce 2s infinite;
    }
  }

  .result-title {
    display: block;
    font-size: $font-size-2xl;
    font-weight: $font-weight-bold;
    color: $dark-gray;
    font-family: $font-family;
    margin-bottom: $spacing-sm;
    text-shadow: 0 2px 4px rgba(255, 255, 255, 0.5);
  }

  .result-subtitle {
    display: block;
    font-size: $font-size-base;
    color: rgba(51, 51, 51, 0.7);
    font-weight: $font-weight-regular;
    font-family: $font-family;
    margin-bottom: $spacing-2xl;
  }

  /* 绘本展示区域 */
  .books-display {
    margin-top: $spacing-2xl;

    .books-grid {
      display: flex;
      justify-content: center;
      gap: $spacing-sm;
      flex-wrap: wrap;
    }

    .book-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      width: 80px;

      .book-cover {
        width: 60px;
        height: 80px;
        border-radius: $border-radius-md;
        box-shadow: $shadow-lg;
        margin-bottom: $spacing-sm;
        background-color: $white-10;
      }

      .book-title {
        font-size: $font-size-sm;
        color: rgba(51, 51, 51, 0.8);
        text-align: center;
        line-height: $line-height-tight;
        max-width: 70px;
        font-family: $font-family;
        @include text-ellipsis-multiline(2);
      }
    }

    .more-books {
      display: flex;
      flex-direction: column;
      align-items: center;
      width: 80px;

      .more-icon {
        width: 60px;
        height: 80px;
        border-radius: $border-radius-md;
        background-color: $white-30;
        border: 2px dashed rgba(51, 51, 51, 0.3);
        @include center-flex;
        margin-bottom: $spacing-sm;

        .more-text {
          font-size: $font-size-md;
          color: rgba(51, 51, 51, 0.7);
          font-weight: $font-weight-semibold;
          font-family: $font-family;
        }
      }

      .more-title {
        font-size: $font-size-sm;
        color: rgba(51, 51, 51, 0.8);
        text-align: center;
        font-family: $font-family;
      }
    }
  }
}

/* 心得填写区域 - 儿童友好风格 */
.content-input-section {
  flex: 1;
  padding: $spacing-md $spacing-2xl 0px $spacing-2xl;

  .content-textarea {
    width: 100%;
    min-height: 200px;
    @include glass-effect;
    border-radius: $border-radius-xl;
    padding: $spacing-2xl;
    font-size: $font-size-md;
    line-height: $line-height-relaxed;
    color: $dark-gray;
    font-family: $font-family;
    border: 2px solid $border-color-light;
    box-sizing: border-box;
    box-shadow: $shadow-lg;
    transition: $transition-all;

    &::placeholder {
      color: $medium-gray;
      font-size: $font-size-base;
    }

    &:focus {
      border-color: $primary-blue;
      outline: none;
      box-shadow: $shadow-blue-lg;
      transform: translateY(-2px);
    }
  }

  .char-count {
    display: flex;
    justify-content: flex-end;
    margin-top: $spacing-sm;
    padding-right: $spacing-xs;

    .count-text {
      font-size: $font-size-sm;
      color: $medium-gray;
      font-weight: $font-weight-medium;
      font-family: $font-family;
    }
  }
}

/* 发布打卡按钮 - 儿童友好风格 */
.publish-section {
  padding: 0 $spacing-2xl 0px $spacing-2xl;
  margin-bottom: 20px;

  .publish-btn {
    width: 100%;
    height: 56px;
    background: $blue-gradient;
    border-radius: $border-radius-3xl;
    border: none;
    @include center-flex;
    transition: $transition-all;
    box-shadow: $shadow-blue-lg;
    position: relative;
    overflow: hidden;
    cursor: pointer;

    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: -100%;
      width: 100%;
      height: 100%;
      background: linear-gradient(90deg, transparent, $white-20, transparent);
      transition: left 0.5s ease;
    }

    &:active:not(.loading) {
      transform: scale(0.98);
      box-shadow: $shadow-blue-lg;

      &::before {
        left: 100%;
      }
    }

    &.loading {
      background: linear-gradient(135deg, #a8a8a8 0%, #888888 100%);
      box-shadow: 0 4px 16px rgba(168, 168, 168, 0.3);

      &::after {
        content: '';
        position: absolute;
        width: 20px;
        height: 20px;
        border: 2px solid $white-30;
        border-top: 2px solid $white;
        border-radius: $border-radius-full;
        animation: spin 1s linear infinite;
        margin-right: $spacing-sm;
      }
    }

    &.disabled {
      background: linear-gradient(135deg, #cccccc 0%, #999999 100%);
      box-shadow: 0 2px 8px rgba(153, 153, 153, 0.2);
      cursor: not-allowed;

      &:active {
        transform: none;
        box-shadow: 0 2px 8px rgba(153, 153, 153, 0.2);
      }

      &::before {
        display: none;
      }

      .btn-text {
        color: #666666;
        text-shadow: none;
      }
    }

    &:disabled {
      opacity: 0.8;
    }

    .btn-text {
      font-size: $font-size-lg;
      font-weight: $font-weight-semibold;
      color: $white;
      font-family: $font-family;
      text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
    }
  }
}

/* 动画效果 */
@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

@keyframes bounce {
  0%,
  20%,
  50%,
  80%,
  100% {
    transform: translateY(0);
  }
  40% {
    transform: translateY(-10px);
  }
  60% {
    transform: translateY(-5px);
  }
}

/* 适配不同屏幕 */
@media (max-height: 700px) {
  .reading-result {
    padding: 20px 20px 15px 20px;

    .result-title {
      font-size: 24px;
    }

    .result-subtitle {
      font-size: 14px;
    }
  }

  .content-input-section {
    padding: 20px 20px 15px 20px;

    .content-textarea {
      min-height: 200px;
      padding: 20px;
    }
  }

  .publish-section {
    padding: 0 20px 30px 20px;

    .publish-btn {
      height: 50px;
      border-radius: 25px;
    }
  }
}

@media (max-height: 600px) {
  .content-input-section {
    .content-textarea {
      min-height: 160px;
      padding: 16px;
    }
  }
}

/* 深色模式适配 */
@media (prefers-color-scheme: dark) {
  .checkin-container {
    background: linear-gradient(180deg, #1a1a1a 0%, #2d2d2d 100%);
  }

  .content-input-section {
    .content-textarea {
      background-color: #2d2d2d;
      color: #fff;
      border-color: #404040;

      &::placeholder {
        color: #888;
      }

      &:focus {
        border-color: #667eea;
        box-shadow: 0 4px 24px rgba(102, 126, 234, 0.25);
      }
    }

    .char-count .count-text {
      color: #aaa;
    }
  }
}

/* blob动画关键帧 */
@keyframes blob-bounce {
  0% {
    transform: translate(-50%, -50%) translate3d(0, 0, 0) scale(1);
  }
  25% {
    transform: translate(-50%, -50%) translate3d(50px, -30px, 0) scale(1.1);
  }
  50% {
    transform: translate(-50%, -50%) translate3d(30px, 50px, 0) scale(0.9);
  }
  75% {
    transform: translate(-50%, -50%) translate3d(-50px, 30px, 0) scale(1.05);
  }
  100% {
    transform: translate(-50%, -50%) translate3d(0, 0, 0) scale(1);
  }
}

/* 弹窗动画关键帧 */
@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(50px) scale(0.9);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

/* 弹窗样式 */
.detail-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(10px);
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: $spacing-lg;
  animation: fadeIn 0.3s ease-out;
}

.detail-modal-content {
  background: $white;
  border-radius: $border-radius-xl;
  width: 90%;
  max-width: 500px;
  max-height: 80vh;
  position: relative;
  box-shadow: $shadow-lg;
  overflow: hidden;
  animation: slideUp 0.3s ease-out;
}

.modal-close-btn {
  position: absolute;
  top: $spacing-md;
  right: $spacing-md;
  width: 32px;
  height: 32px;
  border-radius: $border-radius-full;
  background: rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
  cursor: pointer;
  transition: $transition-all;

  &:hover {
    background: rgba(0, 0, 0, 0.2);
  }
}

.modal-scroll-container {
  height: 100%;
  max-height: 70vh;
}

.modal-divider {
  height: 1px;
  background: $border-color-light;
  margin: 0 $spacing-lg;
}

.modal-books-section {
  padding: $spacing-lg;
}

.modal-books-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: $spacing-md;
}

.modal-book-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;

  .modal-book-cover {
    width: 70px;
    height: 90px;
    border-radius: $border-radius-md;
    margin-bottom: $spacing-sm;
    box-shadow: $shadow-md;
  }

  .modal-book-title {
    font-size: $font-size-sm;
    color: $dark-gray;
    font-family: $font-family;
    font-weight: $font-weight-medium;
    line-height: $line-height-tight;
    text-align: center;
    word-break: break-word;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

.modal-books-header {
  padding: $spacing-lg 0;
  text-align: center;

  .books-header {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: $spacing-sm;

    .books-icon {
      font-size: $font-size-xl;
      margin-right: $spacing-sm;
    }

    .books-title {
      font-size: $font-size-xl;
      color: $dark-gray;
      font-weight: $font-weight-semibold;
      font-family: $font-family;
    }
  }

  .books-count {
    font-size: $font-size-base;
    color: $medium-gray;
    font-family: $font-family;
  }
}

/* 让更多按钮可点击 */
.more-books {
  cursor: pointer;
  transition: $transition-all;

  &:hover {
    transform: translateY(-2px);

    .more-icon {
      background-color: rgba(255, 255, 255, 0.5);
      border-color: rgba(51, 51, 51, 0.5);
    }
  }

  &:active {
    transform: translateY(0) scale(0.98);
  }
}
</style>
